package com.jz.netthings.application.providerCreate.service.impl;

import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jz.netthings.appengine.baseData.ProviderData;
import com.jz.netthings.appengine.baseData.ProviderInfo;
import com.jz.netthings.appengine.queue.MachineMgr;
import com.jz.netthings.appengine.queue.ProviderQueue;
import com.jz.netthings.appengine.support.BeanSupport;
import com.jz.netthings.application.bodyCheck.bean.BodyCheck;
import com.jz.netthings.application.bodyCheck.mapper.mysql.BodyCheckMapper;
import com.jz.netthings.application.providerCreate.bean.ProviderXp;
import com.jz.netthings.application.providerCreate.mapper.mysql.ProviderXpMapper;
import com.jz.netthings.application.providerCreate.service.ProviderInfoService;
import com.jz.netthings.application.providerCreate.service.ProviderXpService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jz.netthings.application.providerReg.bean.ProviderReg;
import com.jz.netthings.application.providerReg.mapper.mysql.ProviderRegMapper;
import com.jz.netthings.application.sample.bean.PlasmaSamples;
import com.jz.netthings.application.sample.mapper.PlasmaSamplesMapper;
import com.jz.netthings.application.utils.AppUtils;
import com.jz.netthings.bean.system.JyUser;
import com.jz.netthings.exception.AdscmSystemException;
import com.jz.netthings.security.utils.Token;
import com.jz.netthings.system.mapper.mysql.JyUserMapper;
import com.jz.netthings.utils.AdscmBaseUtils;
import com.jz.netthings.utils.AdscmDateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zyl
 * @since 2019-03-13
 */
@Service
public class ProviderXpServiceImpl extends ServiceImpl<ProviderXpMapper, ProviderXp> implements ProviderXpService {
    @Autowired
    JyUserMapper jyUserMapper;
    @Value("${ly.upload.baseUrl}")
    String photoUrl;
    @Autowired
    ProviderInfoService providerInfoService;
    @Autowired
    ProviderQueue providerQueue;
    @Autowired
    BodyCheckMapper bodyCheckMapper;
    @Autowired
    ProviderRegMapper providerRegMapper;;
    @Autowired
    private PlasmaSamplesMapper plasmaSamplesMapper;

    /**
     * engine模块的IP和端口
     */
    @Value("${netty.engine.ipAddress}")
    private String engineIp;
    @Value("${netty.engine.serverPort}")
    private String engineServerPort;

    @Override
    public List<ProviderXp> selectByProviderNo(String id) throws AdscmSystemException {
        EntityWrapper<ProviderXp> providerXpWrapper = new EntityWrapper<>();
        providerXpWrapper.eq("providerNo",id);
        List<ProviderXp> providerXps = super.selectList(providerXpWrapper);
        for (ProviderXp providerXp : providerXps) {
            if(AdscmBaseUtils.getInstance().isNotEmpty(providerXp.getCrearor(),null)){
                JyUser jyUser = jyUserMapper.selectById(providerXp.getCrearor());
                if (AdscmBaseUtils.getInstance().isNotEmpty(jyUser,null)){
                    providerXp.setCrearorName(jyUser.getName());
                }else {
                    providerXp.setCrearorName(providerXp.getCrearor());
                }
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(providerXp.getPhoto(),null)){
                providerXp.setPhoto(photoUrl+providerXp.getPhoto());
            }
        }
        return providerXps;
    }
    @Override
    public Boolean insertProviderXp(ProviderXp providerXp, Token token) throws AdscmSystemException {
        providerXp.setCrearor(token.getUser().getId().toString());
        providerXp.setCreateDate(new Date());
          if (AdscmBaseUtils.getInstance().isNotEmpty(providerXp.getPhoto(),null)){
              String photo = providerXp.getPhoto().replace(photoUrl, "");
              providerXp.setPhoto(photo);
          }
        providerXp.setMODIFY_TIME(AdscmDateUtils.getDateFomat(new Date()) );
        providerXp.setSYNDATE(AdscmDateUtils.getDateFomat(AdscmDateUtils.getFormateDate(new Date())));
        providerInfoService.issueCard(providerXp);
        boolean insert = super.insert(providerXp);

        if (insert){
            updateCardId(providerXp);
        }
        return insert;
    }
    @Override
    public Boolean updateProviderXp(ProviderXp providerXp, Token token) throws AdscmSystemException {
        if(AdscmBaseUtils.getInstance().isNotEmpty(providerXp.getPhoto(),null)){
            String photo = providerXp.getPhoto().replace(photoUrl, "");
            providerXp.setPhoto(photo);
            providerXp.setCrearor(token.getUser().getId().toString());
            providerXp.setCreateDate(new Date());
        }
        providerXp.setMODIFY_TIME(AdscmDateUtils.getDateFomat(new Date()) );
        providerXp.setSYNDATE(AdscmDateUtils.getDateFomat(AdscmDateUtils.getFormateDate(new Date())));
        boolean b = super.updateById(providerXp);
        providerInfoService.issueCard(providerXp);
        return b;
    }


    private void updateCardId(ProviderXp providerXp){
        ProviderInfo providerInfo = providerInfoService.selectById(providerXp.getProviderNo());
        if (providerInfo != null && "R".startsWith(providerInfo.getCardId())){
            ProviderData providerData = providerQueue.getByProviderNo(providerInfo.getCardId());
            boolean xpIsPass = true;
            //表示是临时卡号
            //胸片记录已经过了有效期提示拍胸片
            if (new Date().getTime()>providerXp.getValidDate().getTime()){
                xpIsPass = false;
            }
            //胸片不合格
            if ("0".equals(providerXp.getResult())){
                xpIsPass = false;
            }

            if (xpIsPass){
                //查看化检和体检
                boolean flag = true;//是否要修改卡号
                //体检
                if (AdscmBaseUtils.getInstance().isNotEmpty(providerData.isBodyIsPass(),null)){
                    if (!providerData.isBodyIsPass()){
                        flag = false;
                    }
                }else{
                    flag = false;
                }

                //化检
                if (providerData.isNeedAssay()  && !providerData.isAssayIsPass()){
                    flag = false;
                }

                if (flag){
                    //需要修改卡号
                    int num=1;
                    String bloodType = providerInfo.getBloodType();
                    Wrapper<ProviderInfo> providerInfoWrapper=new EntityWrapper<>();
                    providerInfoWrapper.like("cardId",bloodType, SqlLike.RIGHT).orderBy("cardId",false);
                    providerInfoWrapper.last("limit 1");
                    List<ProviderInfo> providerInfoList = providerInfoService.selectList(providerInfoWrapper);

                    if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfoList,null)){

                        Integer tmp = Integer.valueOf(providerInfoList.get(0).getCardId())+1;
                        providerInfo.setCardId(String.valueOf(tmp));
                        providerInfo.setModifyTime(new Date());
                        providerInfoService.updateById(providerInfo);

                        //登记
                        ProviderReg providerRegister = new ProviderReg();
//                            providerRegister.setRegisterNo(providerData.getRegisterNo());
//                            providerRegister.setIdNo(providerData.getIdNo());
                        Wrapper<ProviderReg> wrapper = new EntityWrapper<>();
                        wrapper.eq("registerNo",providerData.getRegisterNo());
                        wrapper.eq("idNo",providerData.getIdNo());
                        List<ProviderReg> regs = providerRegMapper.selectList(wrapper);//.getProviderRegister(providerRegister);
                        if (regs != null && regs.size()>0){
                            ProviderReg reg = regs.get(0);
                            reg.setModifyTime(new Date());
                            providerRegMapper.updateById(reg);
                        }
                        //体检

                        BodyCheck bodyCheck = bodyCheckMapper.selectById(providerData.getBodyCheckId());
                        if (bodyCheck != null){
                            bodyCheck.setMODIFY_TIME(AdscmDateUtils.getDateFomat(new Date()));
                            bodyCheckMapper.updateById(bodyCheck);
                        }

                        //化检
                        PlasmaSamples samples = plasmaSamplesMapper.selectById(providerData.getAssayId());
                        if (samples != null){
                            samples.setMODIFY_TIME(AdscmDateUtils.getDateFomat(new Date()));
                            plasmaSamplesMapper.updateById(samples);
                        }

                    }

//                    MachineMgr.getInstance().sendMsgToAllotCtxs( BeanSupport.loadToAllotMsg(providerData,null));
                    AppUtils.sendMsgToAllotCtxs(providerData,"http://"+engineIp+":"+engineServerPort);
                }


            }else{
                //胸片不过关
                providerInfo.setRefuseDate(new Date());
                providerInfo.setRefuseReason(providerXp.getRemark());
                providerInfo.setProviderState(2);
                providerInfoService.updateById(providerInfo);
            }

        }
    }
}
